
use anyhow::Result;
use hyper::{Request, Response, Client, body};
use hyper::client::HttpConnector;
use std::collections::HashMap;

use serde::{Deserialize, Serialize};
use std::borrow::Borrow;

use crate::miner::{JsonRpcResponse, JsonRpcError};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct SectorId {
    pub miner: u64,
    pub number: u64,
}

pub async fn pledge_on_sector(client: &Client<HttpConnector>, url: &str, token: &str) -> Result<JsonRpcResponse<SectorId>>{
    let body = r#"
{
	"jsonrpc": "2.0",
	"method": "Filecoin.PledgeSector",
	"params": [],
	"id": 1
}
"#;
    let auth = format!("Bearer {}", token);
    let body = body::Body::from(body);

    let request = Request::builder()
        .uri(url)
        .header("Authorization", auth)
        .body(body)?;

    let rsp = client.request(request).await?;
    if rsp.status().is_success() {
        let buf = body::to_bytes(rsp).await?;
        let result: JsonRpcResponse<SectorId> = serde_json::from_slice(buf.borrow())?;
        Ok(result)
    } else {
        Err(anyhow::Error::msg(format!("http request got error response {}", rsp.status())))
    }
}